/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.wxApplet.service;

import com.fzhucc.config.FileProperties;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.appletShow.domain.CmsService;
import com.fzhucc.modules.appletShow.domain.dto.CmsServiceDto;
import com.fzhucc.modules.appletShow.repository.CmsServiceRepository;
import com.fzhucc.modules.appletShow.service.mapstruct.CmsServiceMapper;
import com.fzhucc.modules.expert.domain.Expert;
import com.fzhucc.modules.expert.domain.dto.ExpertDto;
import com.fzhucc.modules.expert.repository.ExpertRepository;
import com.fzhucc.modules.expert.service.mapstruct.ExpertMapper;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.domain.ProjectNotice;
import com.fzhucc.modules.pms.repository.ProjectNoticeRepository;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.SciTechnologyDemandQueryCriteria;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.security.config.WxProperties;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.modules.technical.domain.Technical;
import com.fzhucc.modules.technical.domain.dto.TechnicalDto;
import com.fzhucc.modules.technical.repository.TechnicalRepository;
import com.fzhucc.modules.technical.service.mapstruct.TechnicalMapper;
import com.fzhucc.modules.thinktank.domain.dto.LeaderQueryCriteria;
import com.fzhucc.modules.wxApplet.domain.*;
import com.fzhucc.utils.SecurityUtils;
import com.fzhucc.utils.WxUtils;
import lombok.RequiredArgsConstructor;
import org.jeecg.pms.entity.PmsProject;
import org.jeecg.pms.entity.PmsRace;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-21
 **/
@Service
@RequiredArgsConstructor
public class WxAppletService {

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserService userService;

    private final ProjectNoticeRepository projectNoticeRepository;

    private final CmsServiceRepository cmsServiceRepository;

    private final ExpertRepository expertRepository;

    private final ProjectRepository projectRepository;

    private final TechnicalRepository technicalRepository;

    private final WxProperties wxProperties;

    private final CmsServiceMapper serviceMapper;

    private final ExpertMapper expertMapper;

    private final TechnicalMapper technicalMapper;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${sci.audit.shtg}")
    public String shtg;

    private final SciTechnologyDemandRepository sciTechnologyDemandRepository;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;


    public List<DictDetailDto> findAllUserType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("user_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }


    public DictDetailDto findTypeByTypeId(WxAppletQueryCriteria criteria) {
        if (criteria == null || criteria.getTypeId() == null) {
            throw new BadRequestException("查询参数为null");
        }
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("user_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            for (int i = 0; i < list1.size(); i++) {
                DictDetailDto dictDetailDto = list1.get(i);
                if (dictDetailDto != null) {
                    String value = dictDetailDto.getValue();
                    if (value.equals(criteria.getTypeId())) {
                        return dictDetailDto;
                    }
                }
            }
        }
        return null;
    }

    public List<ProjectNotice> getProjectNoticeWithWxUser() {
        List<ProjectNotice> list_projectNotice = new ArrayList<ProjectNotice>();
        //只查询 到该用户的 最新一条的 推送信息
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("登录用户ID未找到");
        }
        List<Project> list_project = projectRepository.findByUserId(userId);
        for (int i = 0; i < list_project.size(); i++) {
            List<ProjectNotice> list = projectNoticeRepository.findByProjectIdUserIdWithLast(list_project.get(i).getId(), userId);
            if (list != null && list.size() > 0) {
                ProjectNotice projectNotice = list.get(0);
                Optional<ProjectNotice> res = projectNoticeRepository.findById(projectNotice.getId());
                if (res.isPresent()) {
                    //调用一次就删除
                    projectNoticeRepository.deleteById(res.get().getId());
                }
                list_projectNotice.add(projectNotice);
            }
        }
        return list_projectNotice;
    }

    public void getPhone(WxPhoneCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("登录用户ID未找到");
        }
        if (criteria.getCode() == null || criteria.getCode().equals("")) {
            throw new BadRequestException("code未找到");
        }
        String phone = WxUtils.getPhone(wxProperties.getMp().getAppId(),
                wxProperties.getMp().getAppSecret(), criteria.getCode());
        userService.updatePhone(userId, phone);
    }

    public String getPhoneResp(WxPhoneCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("登录用户ID未找到");
        }
        if (criteria.getCode() == null || criteria.getCode().equals("")) {
            throw new BadRequestException("code未找到");
        }
        String phone = WxUtils.getPhone(wxProperties.getMp().getAppId(),
                wxProperties.getMp().getAppSecret(), criteria.getCode());
        return phone;
    }

    public ChangeRandomResp getChangeRandom(ChangeRandomDto dto) {
        List<Integer> cmsServiceIds = dto.getCmsServiceIds();
        List<Integer> expertIds = dto.getExpertIds();
        List<Integer> technicalIds = dto.getTechnicalIds();
        ChangeRandomResp changeRandomResp = new ChangeRandomResp();
        if (cmsServiceIds != null && cmsServiceIds.size() >= 0) {
            for (Integer a : cmsServiceIds) {
                Optional<CmsService> res = cmsServiceRepository.findById(a);
                if (!res.isPresent()) {
                    throw new BadRequestException("服务id未找到");
                }
            }
            if (cmsServiceIds.size() >= 3) {//服务
                List<CmsService> list = cmsServiceRepository.findWithOutIds(cmsServiceIds.get(0), cmsServiceIds.get(1), cmsServiceIds.get(2));
                if (list != null && list.size() > 0) {
                    List<CmsService> randomWithOutIds = cmsServiceRepository.findRandomWithOutIds(cmsServiceIds.get(0), cmsServiceIds.get(1), cmsServiceIds.get(2));
                    if (randomWithOutIds != null) {
                        List<CmsServiceDto> cmsServiceDtos = serviceMapper.toDto(randomWithOutIds);
                        changeRandomResp.setListServices(cmsServiceDtos);
                    }
                } else {
                    //说明除了这3个id 之外 没有其他id满足条件  则还是回传这三个
                    List<CmsService> list2 = cmsServiceRepository.findRandom();
                    if (list2 != null) {
                        List<CmsServiceDto> cmsServiceDtos = serviceMapper.toDto(list2);
                        changeRandomResp.setListServices(cmsServiceDtos);
                    }
                }
            } else {//小于三个说明 数据库里的少于三个 就直接调用随机
                List<CmsService> list = cmsServiceRepository.findRandom();
                if (list != null) {
                    List<CmsServiceDto> cmsServiceDtos = serviceMapper.toDto(list);
                    changeRandomResp.setListServices(cmsServiceDtos);
                }
            }
        }

        if (expertIds != null && expertIds.size() >= 0) {
            for (Integer a : expertIds) {
                Optional<Expert> res = expertRepository.findById(a);
                if (!res.isPresent()) {
                    throw new BadRequestException("专家id未找到");
                }
            }
            if (expertIds.size() >= 3) {//专家
                List<Expert> list = expertRepository.findWithOutIds(expertIds.get(0), expertIds.get(1), expertIds.get(2));
                if (list != null && list.size() > 0) {
                    List<Expert> randomWithOutIds = expertRepository.findRandomWithOutIds(expertIds.get(0), expertIds.get(1), expertIds.get(2));
                    if (randomWithOutIds != null) {
                        List<ExpertDto> expertDtos = expertMapper.toDto(randomWithOutIds);
                        changeRandomResp.setListExperts(expertDtos);
                    }
                } else {
                    //说明除了这3个id 之外 没有其他id满足条件  则还是回传这三个
                    List<Expert> list2 = expertRepository.findRandom();
                    if (list2 != null) {
                        List<ExpertDto> expertDtos = expertMapper.toDto(list2);
                        changeRandomResp.setListExperts(expertDtos);
                    }
                }
            } else {//小于三个说明 数据库里的少于三个 就直接调用随机
                List<Expert> list = expertRepository.findRandom();
                if (list != null) {
                    List<ExpertDto> expertDtos = expertMapper.toDto(list);
                    changeRandomResp.setListExperts(expertDtos);
                }
            }
        }

        if (technicalIds != null && technicalIds.size() >= 0) {
            for (Integer a : technicalIds) {
                Optional<Technical> res = technicalRepository.findById(a);
                if (!res.isPresent()) {
                    throw new BadRequestException("技术经理人id未找到");
                }
            }
            if (technicalIds.size() >= 3) {//技术经理人
                List<Technical> list = technicalRepository.findWithOutIds(technicalIds.get(0), technicalIds.get(1), technicalIds.get(2));
                if (list != null && list.size() > 0) {
                    List<Technical> randomWithOutIds = technicalRepository.findRandomWithOutIds(technicalIds.get(0), technicalIds.get(1), technicalIds.get(2));
                    if (randomWithOutIds != null) {
                        List<TechnicalDto> technicalDtos = technicalMapper.toDto(randomWithOutIds);
                        changeRandomResp.setListTechnicals(technicalDtos);
                    }
                } else {
                    //说明除了这3个id 之外 没有其他id满足条件  则还是回传这三个
                    List<Technical> list2 = technicalRepository.findRandom();
                    if (list2 != null) {
                        List<TechnicalDto> technicalDtos = technicalMapper.toDto(list2);
                        changeRandomResp.setListTechnicals(technicalDtos);
                    }
                }
            } else {//小于三个说明 数据库里的少于三个 就直接调用随机
                List<Technical> list = technicalRepository.findRandom();
                if (list != null) {
                    List<TechnicalDto> technicalDtos = technicalMapper.toDto(list);
                    changeRandomResp.setListTechnicals(technicalDtos);
                }
            }
        }
        return changeRandomResp;
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(WxZqxCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public ZqxLargeIndexDto getAppIndexData(WxZqxCriteria criteria) {
        Integer demands = 0;
        Integer models = 0;
        ZqxLargeIndexDto dto = new ZqxLargeIndexDto();
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }

        if ((criteria.getOrgArea() != null && criteria.getOrgArea() == all) || criteria.getOrgArea() == null) {
            List<SciTechnologyDemand> list = sciTechnologyDemandRepository.findNormal(shtg);
            demands = list.size();
            List<SciPersonnelInfo> list2 = sciPersonnelInfoRepository.findNormal(shtg);
            models = list2.size();
        } else {
            //List<SciTechnologyDemand> list3 = sciTechnologyDemandRepository.findNormalByArea(criteria.getOrgArea());
            List<SciTechnologyDemand> list3 = sciTechnologyDemandRepository.findNormalByLikeArea("%" + criteria.getOrgArea() + "%",shtg);
            demands = list3.size();
            //List<SciPersonnelInfo> list4 = sciPersonnelInfoRepository.findNormalByArea(criteria.getOrgArea());
            List<SciPersonnelInfo> list4 = sciPersonnelInfoRepository.findNormalByLikeArea("%"+ criteria.getOrgArea() + "%",shtg);
            models = list4.size();
        }
        dto.setDemands(demands);
        dto.setModels(models);
        return dto;
    }
}